package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDTO;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WemediaMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WemediaMapper, WmUser> implements WmUserService {
    /**
     * 自媒体登录实现
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(WmUserDTO dto) {
        //1.检查参数  判断用户名和密码是否为空
        if (StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())) {
            //返回错误信息
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码不能为空!");
        }
        //2 查询自媒体用户
        WmUser wmUser = this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        //判断自媒体用户是否为null
        if (wmUser==null) {
            //说明自媒体用户不存在
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在!");
        }
        //判断用户状态是否异常
        if (wmUser.getStatus()!=9) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"用户状态异常!请联系管理员");
        }
        //将密码加密跟数据库中用户密码进行对比
        String md5Pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + wmUser.getSalt()).getBytes(StandardCharsets.UTF_8));
        //判断密码是否相等
        if (!wmUser.getPassword().equals(md5Pwd)) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误了!");
        }
        //创建map集合,封装token
        Map<String,Object> map = new HashMap<>();
        //拿出token
        String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getId()));
        map.put("token",token);
        //将数据封装到vo对象中
        WmUserVO userVO = new WmUserVO();
        BeanUtils.copyProperties(wmUser,userVO);
        //将vo对象封装到map集合中
        map.put("user",userVO);
        //4 返回jwt结果
        return ResponseResult.okResult(map);
    }
}
